package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.entity.Category;
import com.itheima.entity.Movies;
import com.itheima.result.Result;
import com.itheima.service.CategoryService;
import com.itheima.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("category")//作为当前类中所有请求的前缀
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private MovieService movieService;

    @GetMapping("list")
    //@RequestParam单独使用时意味请求中必须携带该参数且有值
    public Result findByPage(
           @RequestParam Integer pageNum,
           @RequestParam Integer pageSize,
            Integer cid,
            String keyword){
        //调用service完成分页条件查询
        PageInfo pageInfo = categoryService.findByPage(pageNum,pageSize,cid,keyword);

        return Result.success(pageInfo);
    }

    @DeleteMapping("deleteById/{id}")
    public Result deleteById(@PathVariable String id){
        //调用service完成删除操作
        //删除前判断当前分类下是否有电影
        List<Movies> list = movieService.selectByCategoryId(id);
        if (!list.isEmpty())
        {
            return Result.error("当前分类下存在关联的电影！");
        }else
        {
            categoryService.deleteById(id);
            return Result.success();
        }
    }

    @DeleteMapping("deleteByIds")
    public Result deleteBatch(Integer[] ids){
        //信号
        int num = 0;
        for (Integer id : ids) {
            List<Movies> movies = movieService.selectByCategoryId(id.toString());
            if (!movies.isEmpty())
            {
                num++;
            }
        }
        if (num>0)
        {
            return Result.error("当前分类下存在关联的电影！");
        }else
        {
            categoryService.deleteBatch(ids);
            return Result.success();
        }
    }


    @GetMapping("findById/{id}")
    public Result findById(@PathVariable String id)
    {
        Category category = categoryService.getByid(id);
        return Result.success(category);
    }

    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Category category)
    {
        categoryService.saveOrUpdate(category);
        return Result.success();
    }
}
